package lotusmonitor

import (
	"context"
	"github.com/filecoin-project/go-jsonrpc"
	"github.com/filecoin-project/lotus/api/apistruct"
	"net/http"
)

type SyncerConfig struct {
	HostAddr string
	AuthToken string
}

type SyncerConnection struct {
	closer jsonrpc.ClientCloser
	api apistruct.FullNodeStruct
}

type Syncer struct {
	config *SyncerConfig
}

func NewSyncer(config *SyncerConfig) *Syncer {
	s := &Syncer{}
	s.config = config
	return s
}

func (s *Syncer) Connection() (*SyncerConnection,error) {
	config := s.config
	headers := http.Header{"Authorization": []string{"Bearer " + config.AuthToken}}
	var api apistruct.FullNodeStruct
	rpcAddr := "ws://" + config.HostAddr + "/rpc/v0"
	closer, err := jsonrpc.NewMergeClient(context.Background(),
		rpcAddr, "Filecoin",
		[]interface{}{&api.Internal, &api.CommonStruct.Internal},
		headers)
	if err != nil {
		return nil, err
	}
	conn := &SyncerConnection{}
	conn.api = api
	conn.closer = closer
	return conn, nil
}

func (conn *SyncerConnection) Close() {
	conn.closer()
}
func (conn *SyncerConnection) API() *apistruct.FullNodeStruct {
	return &conn.api
}


